package com.rf.richfitwheel.admin.iam.service.impl;

import com.rf.richfitwheel.admin.conf.IamPropertiesConfig;
import com.rf.richfitwheel.admin.contants.UrlConstant;
import com.rf.richfitwheel.admin.iam.HttpEntityJsonUtil;
import com.rf.richfitwheel.admin.iam.dao.PortalUserMapper;
import com.rf.richfitwheel.admin.iam.dao.PortalUserOrgMapper;
import com.rf.richfitwheel.admin.iam.model.*;
import com.rf.richfitwheel.admin.iam.service.PortalUserService;
import com.rf.richfitwheel.admin.sys.dao.UserMapper;
import com.rf.richfitwheel.admin.sys.model.Config;
import com.rf.richfitwheel.admin.sys.model.Org;
import com.rf.richfitwheel.admin.sys.model.User;
import com.rf.richfitwheel.admin.sys.model.UserExample;
import com.rf.richfitwheel.admin.sys.service.ConfigService;
import com.rf.richfitwheel.admin.sys.service.OrgService;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.utils.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hushouquan
 */
@Service
public class PortalUserServiceImpl implements PortalUserService{
    private Logger log = LoggerFactory.getLogger(PortalUserServiceImpl.class);
    
    @Autowired
    private IamPropertiesConfig iamPropertiesConfig;
    @Autowired
    private RestTemplate restTemplateOuter;
    @Autowired
    private ConfigService configService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private PortalUserMapper portalUserMapper;
    @Autowired
    private PortalUserOrgMapper portalUserOrgMapper;
    @Autowired
    private UserMapper userMapper;
    
    /**
     * 同步用户数据入库
     *
     * @param appId    与商网集成的唯一编码
     * @param myDate   时间戳
     * @param config 游标
     * @param countSyn 记录数
     */
    @Override
    public Integer userSynDo(String appId, long myDate, Config config, Integer countSyn) throws URISyntaxException, IOException{
        //数据同步的游标
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("hostname", iamPropertiesConfig.getHostnameByAppId(appId));
        CloseableHttpResponse response = HttpEntityJsonUtil.executeApi(iamPropertiesConfig.getAccessKeyByAppId(appId),
                iamPropertiesConfig.getSecretKeyByAppId(appId), appId, "GET", null, headerMap,
                iamPropertiesConfig.getUrl() + UrlConstant.IAM_API_USERS_SYNC, config.getParamValue());
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if(statusCode == org.apache.http.HttpStatus.SC_OK){
            IamReturnUserSyn iamReturnUserSyn = HttpEntityJsonUtil.httpEntityContentToJsonArray(entity, IamReturnUserSyn.class);
            if(iamReturnUserSyn != null && iamReturnUserSyn.getCode() == 0){
                PortalUserSyn portalUserSyn = iamReturnUserSyn.getData();
                List<PortalUser> records = portalUserSyn.getRecords();
                for(PortalUser portalUser : records){
                    portalUser.setId(UuidUtil.get32UUID());
                    portalUser.setMyTime(myDate);
                    portalUserMapper.insert(portalUser);
                    List<PortalUserOrg> jobList = portalUser.getUserJobList();
                    for(PortalUserOrg portalUserOrg : jobList){
                        portalUserOrg.setId(UuidUtil.get32UUID());
                        portalUserOrg.setPortalUserId(portalUser.getId());
                        portalUserOrg.setMyTime(myDate);
                        portalUserOrgMapper.insert(portalUserOrg);
                    }
                }
                countSyn = countSyn + records.size();
                log.info("已同步{}条用户数据", countSyn);
                config.setParamValue(portalUserSyn.getNext_cursor() + "");
                //如果还有记录的话递归继续执行
                if(portalUserSyn.isHas_more()){
                    countSyn = userSynDo(appId, myDate, config, countSyn);
                }
            }else{
                log.warn("调用门户同步机构数据失败：{}", iamReturnUserSyn);
            }
            response.close();
        }else{
            log.error("调用门户同步机构数据失败：{}", EntityUtils.toString(entity));
        }
        return countSyn;
    }
    
    /**
     * 对已入库的数据进行处理
     *
     * @param myDate 时间戳
     */
    @Override
    public void userDeal(long myDate){
        PortalUserExample example = new PortalUserExample();
        PortalUserExample.Criteria criteria = example.createCriteria();
        criteria.andMyTimeEqualTo(myDate);
        List<PortalUser> portalUserList = portalUserMapper.selectByExample(example);
        int count = 0;
        for(PortalUser portalUser : portalUserList){
            User user = null;
            UserExample exampleAccount = new UserExample();
            UserExample.Criteria criteriaAccount = exampleAccount.createCriteria();
            criteriaAccount.andAccountNameEqualTo(portalUser.getUserId());
            List<User> listByAccount = userMapper.selectByExample(exampleAccount);
            if(!listByAccount.isEmpty()){
                user = listByAccount.get(0);
            }
            if(user == null && StringUtils.isNotBlank(portalUser.getGroupCode())){
                UserExample exampleU = new UserExample();
                UserExample.Criteria criteriaU = exampleU.createCriteria();
                criteriaU.andStaffIdEqualTo(portalUser.getGroupCode());
                List<User> u1 = userMapper.selectByExample(exampleU);
                if(!u1.isEmpty()){
                    user = u1.get(0);
                }
            }
            if(user == null){
                //新增用户
                user = new User();
                user.setId(UuidUtil.get32UUID());
                user.setUsername(StringUtils.isBlank(portalUser.getGroupCode()) ? portalUser.getUserName() : portalUser.getGroupCode());
                user.setEmail(portalUser.getEmail());
                user.setMobile(portalUser.getMobile());
                user.setStatus(Constant.USER_STATUS_NORMAL);
                user.setCreateUserId(Constant.SUPER_ADMIN);
                user.setCreateTime(new Date(myDate));
                user.setStaffId(portalUser.getGroupCode());
                user.setStaffName(StringUtils.isBlank(portalUser.getDisplayName()) ? portalUser.getUserName() : portalUser.getDisplayName());
                user.setIdType("01");
                user.setIdNo(portalUser.getIdNumber());
                user.setSkin("blue");
                user.setAccountName(portalUser.getUserId());
                user.setTenantId(Constant.SUPER_ADMIN_TENANTID);
                user.setType("1");
                user.setRelationType("2");
                PortalUserOrgExample exampleC = new PortalUserOrgExample();
                PortalUserOrgExample.Criteria criteriaC = exampleC.createCriteria();
                criteriaC.andPortalUserIdEqualTo(portalUser.getId());
                List<PortalUserOrg> listC = portalUserOrgMapper.selectByExample(exampleC);
                PortalUserOrg portalUserOrgC = listC.stream().filter(m -> Constant.COMMON_YES_OR_NO_YES.equals(m.getMainJobOrg())).findFirst().get();
                if(portalUserOrgC.getCompanyId() != null){
                    Org org = orgService.selectById(portalUserOrgC.getCompanyId());
                    user.setEnterpriseId(org == null ? null : org.getOrgCode());
                    user.setEnterpriseName(org == null ? null : org.getOrgName());
                    user.setOrgId(portalUserOrgC.getDeptId());
                }
                try{
                    userMapper.insertSelective(user);
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                }
            }else{
                user.setUsername(StringUtils.isBlank(portalUser.getGroupCode()) ? portalUser.getUserName() : portalUser.getGroupCode());
                user.setEmail(portalUser.getEmail());
                user.setMobile(portalUser.getMobile());
                user.setStaffId(portalUser.getGroupCode());
                user.setStaffName(portalUser.getDisplayName());
                user.setIdNo(portalUser.getIdNumber());
                user.setAccountName(portalUser.getUserId());
                user.setLastChangeder(Constant.SUPER_ADMIN);
                user.setLastChnagedTime(new Date());
                user.setRelationType("2");
                //暂时不更改所属机构
                /*PortalUserOrgExample exampleC = new PortalUserOrgExample();
                PortalUserOrgExample.Criteria criteriaC = exampleC.createCriteria();
                criteriaC.andPortalUserIdEqualTo(portalUser.getId());
                List<PortalUserOrg> listC = portalUserOrgMapper.selectByExample(exampleC);
                PortalUserOrg portalUserOrgC = listC.stream().filter(m -> Constant.COMMON_YES_OR_NO_YES.equals(m.getMainJobOrg())).findFirst().get();
                if(portalUserOrgC.getCompanyId() != null){
                    Org org = orgService.selectById(portalUserOrgC.getCompanyId());
                    user.setEnterpriseId(org == null ? null : org.getOrgCode());
                    user.setEnterpriseName(org == null ? null : org.getOrgName());
                    user.setOrgId(portalUserOrgC.getDeptId());
                }*/
                try{
                    userMapper.updateByPrimaryKeySelective(user);
                    /*if(user.getId().equals(portalUser.getUserId())){
                        //id相同说明是通过id查出来的，根据id更新即可
                        userMapper.updateByPrimaryKeySelective(user);
                    }else{
                        //说明是通过用户名查出来，通过用户名来更新(包括id)
                        UserExample exampleP = new UserExample();
                        UserExample.Criteria criteriaP = exampleP.createCriteria();
                        criteriaP.andUsernameEqualTo(user.getUsername());
                        user.setId(portalUser.getUserId());
                        userMapper.updateByExample(user, exampleP);
                    }*/
                }catch(Exception e){
                    log.error(e.getMessage(), e);
                }
            }
            count++;
            if(count % 500 == 0 || count == portalUserList.size()){
                log.info("已处理{}/{}条数据", count, portalUserList.size());
            }
        }
        log.info("共处理{}条数用户数据", portalUserList.size());
    }
}
